package com.dzsw.netty.websocket;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.HandshakeComplete;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
@Sharable
public class WebSocketHandshakeTrigger extends ChannelInboundHandlerAdapter {

	public static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(50);
	public final static WebSocketHandshakeTrigger INSTANCE = new WebSocketHandshakeTrigger();

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception {
		if (event instanceof HandshakeComplete) {
			log.debug("client -> " + ctx.channel().remoteAddress() + " HandshakeComplete " + "->" + event);

			ctx.pipeline().addLast("BinaryHandler", BinaryFrameHandler.INSTANCE);
			ctx.pipeline().addLast("HeartbeatHandler", HeartbeatHandler.INSTANCE);
			ctx.pipeline().addLast("RequestHandler", RequestHandler.INSTANCE);
//			ctx.pipeline().addLast("PingPongHandler", PingPongHandler.INSTANCE);
			ctx.pipeline().addLast("TextWebSocketFrameHandler", TextWebSocketFrameHandler.INSTANCE);

			//握手成功加入心跳任务
			ScheduledFuture<?> heartbeatTask = scheduler.scheduleAtFixedRate(()-> {
				log.debug("start heartbeatTask --> "  + ctx.channel().remoteAddress());
				ctx.channel().writeAndFlush(new PingWebSocketFrame());
			}, 5, 15, TimeUnit.SECONDS);
			//Channel关闭事件里需要取消心跳任务
			ctx.channel().closeFuture().addListener((ChannelFuture future) -> {
				log.debug("cancel heartbeatTask --> " + ctx.channel().remoteAddress());
				heartbeatTask.cancel(true);
			});

        } else {
            super.userEventTriggered(ctx, event);
        }
	}

}
